<template>
  <div>
    <el-card class="box-card">
      <div>
        <el-alert title="消息提示的文案" type="info" center show-icon>
        </el-alert>
      </div>
      <div class="schedule">
        <el-steps
          :space="200"
          :active="activeName * 1"
          finish-status="success"
          :align-center="true"
        >
          <el-step
            v-for="(item, index) in title"
            :key="index"
            :title="item"
          ></el-step>
        </el-steps>
      </div>
      <div>
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeName"
          @tab-click="handleClick"
          :before-leave="before"
        >
          <el-tab-pane label="基本信息" name="0">
            <div class="message">
              <el-form
                :model="addForm"
                :rules="addFormRules"
                ref="ruleForm"
                class="demo-ruleForm"
              >
                <el-form-item label="商品名称" prop="goods_name">
                  <el-input v-model="addForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                  <el-input
                    type="number"
                    v-model="addForm.goods_price"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                  <el-input
                    type="number"
                    v-model="addForm.goods_weight"
                  ></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input
                    type="number"
                    v-model="addForm.goods_number"
                  ></el-input>
                </el-form-item>
                <!-- <p>分类id:{{ addForm.goods_cat }}---- 当前id:{{ cate_id }}</p> -->
                <el-form-item label="商品分类" prop="region"
                  ><br />
                  <div class="select">
                    <el-cascader
                      v-model="addForm.goods_cat"
                      :options="classify"
                      :props="defaultProps"
                    ></el-cascader>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form>
              <el-form-item
                v-for="(item, index) in dynamicData"
                :key="index"
                :label="item.attr_name"
              >
                <div class="checkbox">
                  <br />
                  <div>
                    <el-checkbox
                      v-for="(item1, index1) in item.attr_vals"
                      :key="index1"
                      v-model="item.attr_vals"
                      :label="item1"
                      size="mini"
                      border
                    ></el-checkbox>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form>
              <el-form-item
                v-for="(item, index) in staticData"
                :key="index"
                :label="item.attr_name"
              >
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <div class="ThePicture">
              <el-upload
                class="upload-demo"
                action="http://www.ysqorz.top:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handlesuccess"
                :headers="headersObj"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <div class="el-button-box">
              <el-button type="primary" @click="add"> 添加 </el-button>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="完成" name="5">完成</el-tab-pane> -->
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
import { GoodsClassify, ParameterListAPI, AddCommodity } from "../../http/api";
export default {
  data() {
    return {
      headersObj: {
        //这是文件上传的请求头
        Authorization: sessionStorage.getItem("token"),
      },
      title: [
        "基本信息",
        "商品参数",
        "商品属性",
        "商品图片",
        "商品内容",
        "完成",
      ],
      tabPosition: "left",
      activeName: "0",
      // activeName1: "0",
      ruleForm: {
        name: "",
      },
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      //表单检验规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 获取三级联动数据
      classify: [],
      // 配置三级联动
      defaultProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      dynamicData: [],
      staticData: [],
    };
  },
  created() {
    this.AddGoods();
  },
  methods: {
    async AddGoods() {
      //请求商品分类列表 级联
      const res = await GoodsClassify();
      console.log(res);
      this.classify = res;
    },
    // 利用标签页的钩子函数
    before(activeName, oldActiveName) {
      console.log(activeName, oldActiveName);
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        this.$message.error("请选择三级");
        return false;
      }
    },
    async handleClick() {
      // 判断下标来请求动态和静态数据
      if (this.activeName === "1") {
        // 参数列表
        const res = await ParameterListAPI(this.cate_id, {
          sel: "many",
        });
        console.log(res);
        res.forEach((item) => {
          item.attr_vals = item.attr_vals.split(/\s+/g);
        });
        this.dynamicData = res;
      } else if (this.activeName === "2") {
        const res = await ParameterListAPI(this.cate_id, {
          sel: "only",
        });
        console.log(res);
        this.staticData = res;
      }
    },
    // 文件上传成功的事件
    handlesuccess(res) {
      console.log(res);
    },
    handlePreview() {},
    handleRemove(file) {
      //删除上传的图片
      console.log(file);
      let deletePath = file.response.data.tmp_path; //获取上传的图片路径
      let i = this.addForm.pics.findIndex((item) => {
        return item.pic === deletePath;
      });
      console.log(i);
      this.addForm.pics.splice(i, 1);
    },
    async add() {
      this.$refs.ruleForm.validate((valid) => {
        //给表单做验证
        if (!valid) {
          return this.$message.error("请填写完整");
        }
      });
      // console.log(this.addForm);
      let froms = _.cloneDeep(this.addForm); //把数据深拷贝一份
      froms.goods_cat = froms.goods_cat.join(","); //分割字符串
      // console.log(froms);
      // console.log("动态参数:", this.dynamicData);
      let dtData = this.dynamicData.map((item) => {
        if (item.attr_vals.join(",").trim().length > 0) {
          return {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
        }
      });
      dtData = dtData.filter((item) => {
        return item;
      });
      console.log("动态参数dtDate:", dtData);

      let jtData = this.staticData.map((item) => {
        if (item.attr_vals.trim().length > 0) {
          return {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
        }
      });
      jtData = jtData.filter((item) => {
        return item;
      });

      console.log("静态参数:", jtData);
      this.addForm.attrs = [...dtData, ...jtData];
      console.log(this.addForm.attrs);
      froms.attrs = this.addForm.attrs;
      console.log(froms); //添加商品接口
      const res = await AddCommodity(froms);

      console.log(res);
      this.AddGoods();
      this.$message({
        message: "创建成功",
        type: "success",
      });
      this.$router.push({ path: "/goods" });
    },
  },
  computed: {
    cate_id() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[this.addForm.goods_cat.length - 1];
      } else {
        return null;
      }
    },
  },
};
</script>
<style lang="scss">
.ql-editor {
  height: 300px !important;
}
</style>
<style lang="scss" scoped>
.el-select {
  width: 20%;
}
.select {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}
</style>
<style lang="scss" scoped>
.schedule {
  margin-top: 20px;
}
.message {
  width: 100%;
  margin-top: 10px;
}
.checkbox {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}
.ThePicture {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}
.el-button-box {
  display: flex;
  justify-content: flex-start;
  .el-button {
    margin-top: 15px;
  }
}
</style>